package com.demo.gulimall.cart.interceptor;

import com.alibaba.fastjson.JSON;
import com.demo.gulimall.auth.entity.Member;
import com.demo.gulimall.cart.vo.UserInfoVo;
import com.demo.gulimall.common.constant.AuthConstant;
import com.demo.gulimall.common.constant.CartConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.*;
import java.util.*;

/**
 * @author Chen Yuan
 * @create 2023-06-19  14:34
 */
@Slf4j
public class CartInterceptor implements HandlerInterceptor {
	// ThreadLocal 同一个线程共享数据
	public static ThreadLocal<UserInfoVo> threadLocal = new ThreadLocal<>();

	// 拦截器, 判断是否登录, 获取临时 Cookie
	@Override
	public boolean preHandle(HttpServletRequest request,
	                         HttpServletResponse response,
	                         Object handler) throws Exception{
		UserInfoVo userInfoVo = new UserInfoVo();
		HttpSession session = request.getSession();
		Member member = (Member) session.getAttribute(AuthConstant.LOGIN_USER);
		if (null != member) {
			// 用户已登录
			userInfoVo.setUserId(member.getId());
		}

		Cookie[] cookies = request.getCookies();

		if (cookies != null && cookies.length > 0) {
			for (Cookie cookie : cookies) {
				if (Objects.equals(CartConstant.TEMP_USER_COOKIE_NAME, cookie.getName())){
					userInfoVo.setUserKey(cookie.getValue());
					userInfoVo.setTempUser(true);
				}
			}
		}

		if (StringUtils.isEmpty(userInfoVo.getUserKey())) {
			// 第一次进入网站, 连临时 Token 都没有, 则生成一个临时的
			String tempKey = UUID.randomUUID().toString();
			userInfoVo.setUserKey(tempKey);
		}

		// 目标方法执行之前, 将用户信息放入 ThreadLocal
		threadLocal.set(userInfoVo);
		log.info("--> 拦截器 - userInfoVo:{}", JSON.toJSONString(userInfoVo));

		return true;
	}


	// 业务执行之后
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

		UserInfoVo userInfoVo = threadLocal.get();
		if (!userInfoVo.isTempUser()){
			// 如果是第一次访问, 将上面生成的临时Key存入Cookie, 以后前端调用都要带上
			Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoVo.getUserKey());
			//cookie.setDomain("mall.com");
			cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
			response.addCookie(cookie);
		}
	}
}
